package com.jdk.demo.mappedByteBuffer;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Test16_1 {
	
	// 只读模式
	public static void main(String[] args) throws Exception {
		File file = new File("n.txt");
		RandomAccessFile fileA = new RandomAccessFile(file, "rw");
		FileChannel fileChannelA = fileA.getChannel();
		MappedByteBuffer buffer = fileChannelA.map(FileChannel.MapMode.READ_ONLY, 0, 5);
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // a
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // b
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // c
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // d
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // e
		System.out.println();
		
		buffer = fileChannelA.map(FileChannel.MapMode.READ_ONLY, 2, 2);
		// 缓冲区第0的位置值是c
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // c
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // d
		Thread.sleep(500);
		System.out.println();
		
		// 下面程序出现异常，因为超出映射的范围
		System.out.println((char)buffer.get() + " position=" + buffer.position()); // d
		
		fileA.close();
		fileChannelA.close();
	}

}
